#!/usr/bin/env bash
# Copyright Kani Contributors
# SPDX-License-Identifier: Apache-2.0 OR MIT

set -eu

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
REPO_DIR="$(dirname $SCRIPT_DIR)"

shopt -s nullglob
KANI_DRIVER="$REPO_DIR/target/kani/bin/kani-driver"

if [[ ! -x ${KANI_DRIVER} ]]
then
    echo "ERROR: Could not find kani-driver binary."
    echo "Looked for: '${KANI_DRIVER}'"
    echo "Was Kani successfully built first?"
    exit 1
fi

FLAMEGRAPH_DIR="flamegraphs"
FLAMEGRAPH_SAMPLING_RATE=8000 # in Hz

FLAMEGRAPH_DRIVER=0
if [[ ( -n "${FLAMEGRAPH:-}" ) && ( "${FLAMEGRAPH}" == "driver" ) ]]; then
    FLAMEGRAPH_DRIVER=1
fi

if (( FLAMEGRAPH_DRIVER == 0 )); then 
    exec -a cargo-kani "${KANI_DRIVER}" "$@"
else 
    mkdir -p "${FLAMEGRAPH_DIR}"
    DATE_POSTFIX=$(date +"%Y-%m-%dT%H:%M:%S")
    exec -a cargo-kani samply record -r $FLAMEGRAPH_SAMPLING_RATE -o "${FLAMEGRAPH_DIR}/driver-${DATE_POSTFIX}.json.gz" --save-only "${KANI_DRIVER}" "$@"
fi